package com.flying.tradingservice.controller;

import com.flying.stockquotes.model.Quote;
import com.flying.tradingservice.model.TradingCompanySummary;
import com.flying.tradingservice.service.QuoteClient;
import com.flying.tradingservice.service.TickerNotFoundException;
import com.flying.tradingservice.service.TradingCompanyClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

@Slf4j
@RestController
public class QuoteController {
    private TradingCompanyClient tradingCompanyClient;
    private QuoteClient quoteClient;

    public QuoteController(TradingCompanyClient tradingCompanyClient, QuoteClient quoteClient) {
        this.tradingCompanyClient = tradingCompanyClient;
        this.quoteClient = quoteClient;
    }

    @GetMapping(value = "/quotes/feed", produces = {MediaType.TEXT_EVENT_STREAM_VALUE})
    public Flux<Quote> quotesFeed() {
        return this.quoteClient.quotesFeed();
    }

    @GetMapping(value = "/quotes/summary/{ticker}", produces = {MediaType.APPLICATION_JSON_VALUE})
    public Mono<TradingCompanySummary> quotesDetails(@PathVariable String ticker) {
        return tradingCompanyClient.getTradingCompany(ticker)
                .zipWith(this.quoteClient.getLatestQuote(ticker), TradingCompanySummary::new);
    }

    @ResponseStatus(HttpStatus.NOT_FOUND)
    @ExceptionHandler(TickerNotFoundException.class)
    public void onTickerNotFound(TickerNotFoundException exception) {
        log.info("In QuoteController.", exception);
    }
}